from django.contrib.auth.hashers import make_password
from rest_framework import serializers

from myapp.models import User, UserType


class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField(min_length=5, required=True)
    password = serializers.CharField(max_length=20, required=True)
    phone = serializers.CharField(max_length=11, min_length=11)


class UserSerializer1(serializers.ModelSerializer):
    repassword = serializers.CharField(max_length=128, write_only=True, required=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'phone', 'repassword']

    # 自定义验证确认密码
    def validate(self, attrs):
        if attrs['password'] != attrs['repassword']:
            attrs['flag'] = False
        return attrs

    # 自定义创建函数，增加密码加密。原默认create()函数不加密
    def create(self, validated_data):
        username = validated_data['username']
        password = validated_data['password']
        phone = validated_data['phone']

        password = make_password(password)
        user = User.objects.create(username=username, password=password, phone=phone)

        return user


class UserTypeSerializer(serializers.ModelSerializer):
    # 名称必需与模型里声明的外键关系一样，many=True是对多个序列化，这样显示用户名字
    # users = serializers.StringRelatedField(many=True)

    # 这样显示用户的id
    # users = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    # 这样显示用户链接，要构建url，且url的名字与这里声明的view_name一样
    users = serializers.HyperlinkedIdentityField(many=True,read_only=True,view_name='user-detail')

    class Meta:
        model = UserType
        fields = ['id', 'name', 'users']


class SingleUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['username', 'password', 'phone', 'usertype']
